﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;

namespace PCS.Utilities.Web
{
    public class FormsAuthenticationHelper
    {
        public static void RedirectFromLoginPage(string userName, string[] roles, TimeSpan timeOut, string defaultReturnUrl, bool createPersistentCookie)
        {
            // Create a new ticket used for authentication

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
               1, // Ticket version

               userName, // Username associated with ticket

               DateTime.Now, // Date/time issued

               DateTime.Now.Add(timeOut), // Date/time to expire

               createPersistentCookie, // "true" for a persistent user cookie

               String.Join(",", roles), // User-data, in this case the roles

               FormsAuthentication.FormsCookiePath);// Path cookie valid for


            // Encrypt the cookie using the machine key for secure transport

            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(
            FormsAuthentication.FormsCookieName, // Name of auth cookie

            hash); // Hashed ticket



            // Set the cookie's expiration time to the tickets expiration time

            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            cookie.Path = FormsAuthentication.FormsCookiePath;
            // Add the cookie to the list for outgoing response

            HttpContext.Current.Response.Cookies.Add(cookie);

            // Redirect to requested URL, or homepage if no previous page

            // requested

            string returnUrl = HttpContext.Current.Request.QueryString["ReturnUrl"];
            if (string.IsNullOrEmpty(returnUrl))
                returnUrl = defaultReturnUrl;

            // Don't call FormsAuthentication.RedirectFromLoginPage since it

            // could

            // replace the authentication ticket (cookie) we just added

            HttpContext.Current.Response.Redirect(returnUrl);
        }

        public static void AuthenticateRequest()
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id =
                            (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        // Get the stored user-data, in this case, our roles
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                }
            }
        }

        public static void RedirectToLoginPage(string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
            }
            else
            {
                HttpContext.Current.Response.Redirect(string.Format("{0}?ReturnUrl={1}",
                    FormsAuthentication.LoginUrl, returnUrl), true);
            }
        }
    }
}
